//
//  LoginViewController.m
//  Recipe
//
//  Created by bing han on 12-7-3.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import "BaseUrl.h"
#import "JSONKit.h"
#import "User.h"
#import "SettingViewController.h"
#import "AppDelegate.h"
#import "DisherViewController.h"
@interface LoginViewController ()

@end

@implementation LoginViewController
@synthesize splitViewController = _splitViewController;

@synthesize table = _table;
@synthesize tlabArry = _tlabArry, ttxtArry=_ttxtArry;
@synthesize tfname = _tfname, tfpass = _tfpass,tfsave=_tfsave;
 
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void) viewWillAppear:(BOOL)animated{
    _table.backgroundView.alpha = 0;
    [self.navigationController setNavigationBarHidden:YES];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    bool issave = [defaults boolForKey:@"savepass"];
    if (issave) {
        NSString *uname = [defaults objectForKey:@"username"];
        NSString *upass = [defaults objectForKey:@"password"];
        
        [self login:uname pass:upass];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    _table = nil;
    _ttxtArry = nil;
    _tlabArry = nil;
    _tfname = nil;
    _tfpass = nil;
    _tfsave = nil;
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(IBAction)tologin:(id)sender{

    NSString *uname = _tfname.text;
    NSString *upass = _tfpass.text;
    bool issave = _tfsave.isOn;
    
    if (issave) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:uname forKey:@"username"];
        [defaults setObject:upass forKey:@"password"];
        [defaults setBool:YES forKey:@"savepass"];
    }
    if ([uname isEqualToString:@""] || uname==nil || [upass isEqualToString:@""] || upass==nil) {
        NSArray *param = [[NSArray alloc] initWithObjects:@"提示",@"请输入完整用户信息",@"确定", nil];
        [self showMsg:param];
        return;
    }
    [self login:uname pass:upass];
}

-(void) login:(NSString *)uname pass:(NSString *)upass{
    NSString *urlStr = [[NSString alloc] initWithString:LOGINURL];
    urlStr = [urlStr stringByAppendingFormat:@"&username="];
    urlStr = [urlStr stringByAppendingString:uname];
    urlStr = [urlStr stringByAppendingFormat:@"&password="];
    urlStr = [urlStr stringByAppendingString:upass];
    
    NSURL *url = [NSURL URLWithString:urlStr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];
    [request startSynchronous];
}

#pragma mark asihttprequest delegate
-(void) requestFinished:(ASIHTTPRequest *)request{

    // 当以文本形式读取返回内容时用这个方法
    NSString *responseString = [request responseString];
    NSDictionary *json = [responseString objectFromJSONString];
    if ([[json objectForKey:@"login"] isEqualToString:@"yes"]) {
        NSString *name = [json objectForKey:@"cnname"];
//        NSArray *param = [[NSArray alloc] initWithObjects:@"欢迎",name,@"确定", nil];
        
//        [self showMsg:param];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        bool issave = [defaults boolForKey:@"savepass"];
        if (issave) {
            [User newInstance].uid = [defaults objectForKey:@"username"];
        }else {
            [User newInstance].uid = _tfname.text;
        }

        [User newInstance].uname = name;
        [name release];
        DisherViewController *disherView = [[DisherViewController alloc] initWithNibName:@"DisherViewController" bundle:nil];
        [self.navigationController pushViewController:disherView animated:YES];
        [disherView release];

    }else{
        NSArray *param = [[NSArray alloc] initWithObjects:@"提示",@"请重新输入您的登陆信息",@"确定", nil];
        [self showMsg:param];
    }
//    NSLog(@"message is %@",[json objectForKey:@"login"]);
}

-(void) requestFailed:(ASIHTTPRequest *)request{
//    NSError *error = [request error];
    NSArray *param = [[NSArray alloc] initWithObjects:@"提示",@"网络错误，请稍后再试。",@"确定", nil];
    [self showMsg:param];
}

-(void) showMsg:(NSArray *) param{

    UIAlertView *showMsg = [[UIAlertView alloc] initWithTitle:[param objectAtIndex:0]  message:[param objectAtIndex:1] delegate:self cancelButtonTitle:[param objectAtIndex:2] otherButtonTitles:nil];
    [showMsg show];
//    [showMsg release];
}

#pragma 
#pragma mark tableview delegate
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId=@"editcell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId] autorelease];
    }
    if (indexPath.row ==0) {
        cell.textLabel.text = @"用户名";
        _tfname = [[[UITextField alloc] initWithFrame:CGRectMake(80, 10, 170, 32)] autorelease];
        _tfname.placeholder = @"请输入用户名";
        [_tfname setDelegate:self];
        [cell.contentView addSubview:_tfname];
    }
    if (indexPath.row ==1) {
        cell.textLabel.text = @"密码";
        _tfpass = [[[UITextField alloc] initWithFrame:CGRectMake(80, 10, 170, 32)] autorelease];
        _tfpass.placeholder = @"请输入密码";
        [_tfpass setSecureTextEntry:YES];
        [_tfpass setDelegate:self];
        [cell.contentView addSubview:_tfpass];
    }
    if (indexPath.row ==2) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        bool issave = [defaults boolForKey:@"savepass"];
        cell.textLabel.text = @"保存密码";
        _tfsave = [[UISwitch alloc] initWithFrame:CGRectMake(120, 10, 100, 32)];
        [_tfsave setOn:issave];
        [cell.contentView addSubview:_tfsave];
    }

    return cell;
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

#pragma --
#pragma mark -- textfield delegate
-(BOOL) textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return  YES;
}

@end
